package cn.hebutrun.oulabot.quartz;

import lombok.RequiredArgsConstructor;
import org.quartz.Scheduler;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @author zhaolong
 * @since 2022-03-24
 */
@Configuration
@RequiredArgsConstructor
public class QuartzConfig {
  private final DataSource dataSource;
  private final CustomJobFactory customJobFactory;

  @Bean
  public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
    SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
    schedulerFactoryBean.setSchedulerName("default_scheduler");
    schedulerFactoryBean.setDataSource(dataSource);
    schedulerFactoryBean.setApplicationContextSchedulerContextKey("application");
    schedulerFactoryBean.setQuartzProperties(quartzProperties());
    schedulerFactoryBean.setTaskExecutor(schedulerThreadPool());
    schedulerFactoryBean.setJobFactory(customJobFactory);
    // 延迟启动
    schedulerFactoryBean.setStartupDelay(5);
    return schedulerFactoryBean;
  }

  @Bean
  public Executor schedulerThreadPool() {
    ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
    threadPoolTaskExecutor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
    threadPoolTaskExecutor.setMaxPoolSize(Runtime.getRuntime().availableProcessors());
    threadPoolTaskExecutor.setQueueCapacity(Runtime.getRuntime().availableProcessors());
    return threadPoolTaskExecutor;
  }

  @Bean
  public Properties quartzProperties() throws IOException {
    PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
    //    propertiesFactoryBean.setLocation(new ClassPathResource("/spring-quartz.yml"));
    propertiesFactoryBean.afterPropertiesSet();
    return propertiesFactoryBean.getObject();
  }

  @Bean
  public Scheduler defaultScheduler() throws IOException {
    return this.schedulerFactoryBean().getScheduler();
  }
}
